// pages/checkReport/index.js
const upload = require('../../utils/upload.js')
const { genReport, modifyReport } = require('../../api/api.js')
const { formatTime } = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dateTimePopupShow: false,
    dateTimePickerFormatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    minDate: 1672531200000, // 2023-01-01
    city: '',
    house: '',
    building: '',
    area: '',
    delegateName: '',
    delegatePhone: '',
    checker: '',
    checkDate: '',
    checkDateFormat: '',
    signatureImgPath: '',
    signatureImgId: '',
    "problemOne": "",
    "problemOneImage": [],
    "problemTwo": "",
    "problemTwoImage": [],
    "problemThree": "",
    "problemThreeImage": [],
    "problemFour": "",
    "problemFourImage": [],
    "problemFive": "",
    "problemFiveImage": [],
    "problemSix": "",
    "problemSixImage": [],
    "problemSeven": "",
    "problemSevenImage": [],
    "problemEight": "",
    "problemEightImage": [],
    "problemNine": "",
    "problemNineImage": [],
    "problemTen": "",
    "problemTenImage": [],
    remark: '',
  },
  handleCityPickerChange(e) {
    this.setData({
      city: e.detail.value
    })
  },
  handleDateTimePickerTap() {
    this.setData({
      dateTimePopupShow: true,
    })
  },
  handleDateTimePickerConfirm(value) {
    this.setData({
      dateTimePopupShow: false,
      checkDate: value.detail,
      checkDateFormat: formatTime(new Date(value.detail))
    })
  },
  handleDateTimePickerCancel() {
    this.setData({
      dateTimePopupShow: false,
    })
  },
  handlePreviewImage(e) {
    const { index, image } = e.target.dataset
    const images = this.data[`problem${image}Image`]
    const urls = images.map(image => image.fileUrl);
    const current = urls[index];
    wx.previewImage({
      urls,
      current
    })
  },
  handleDeleteImage(e) {
    const { index, image } = e.currentTarget.dataset
    const key = `problem${image}Image`;
    const images = this.data[key]
    this.setData({
      [key]: [...images.slice(0, index), ...images.slice(index + 1)]
    })
  },
  uploadImage(count, cb) {
    wx.chooseMedia(
      {
        count: count, // 默认9 
        mediaType: ['image'],
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        async success(res) {
          const result = await Promise.all([...res.tempFiles.map(tempFile => upload(tempFile.tempFilePath))])
          cb(result)
        },
        fail(res) {
          console.log('fail', res)
        }
      }
    )
  },
  goSignature() {
    wx.navigateTo({
      url: '/pages/signature/index',
    })
  },
  deleteSignature() {
    this.setData({
      signatureImgPath: '',
      signatureImgId: ''
    })
  },
  handleAddImage(e) {
    const { image } = e.currentTarget.dataset
    const key = `problem${image}Image`;
    const images = this.data[key]
    this.uploadImage(9 - images.length, (res) => {
      const newImages = res.map(item => {
        const { data } = item
        return data
      })
      this.setData({
        [key]: [...images, ...newImages]
      })
    })
  },
  async submit() {
    const {
      city,
      house,
      building,
      area,
      delegateName,
      delegatePhone,
      checker,
      checkDate,
      problemOne,
      problemOneImage,
      problemTwo,
      problemTwoImage,
      problemThree,
      problemThreeImage,
      problemFour,
      problemFourImage,
      problemFive,
      problemFiveImage,
      problemSix,
      problemSixImage,
      problemSeven,
      problemSevenImage,
      problemEight,
      problemEightImage,
      problemNine,
      problemNineImage,
      problemTen,
      problemTenImage,
      remark,
      signatureImgPath,
      signatureImgId } = this.data;
    if (!city) {
      wx.showToast({
        title: '请选择城市',
        icon: 'none',
      })
      return
    }
    if (!house) {
      wx.showToast({
        title: '请输入楼盘名',
        icon: 'none',
      })
      return
    }
    if (!building) {
      wx.showToast({
        title: '请输入楼栋号-房号',
        icon: 'none',
      })
      return
    }
    if (!area) {
      wx.showToast({
        title: '请输入面积',
        icon: 'none',
      })
      return
    }
    if (!delegateName) {
      wx.showToast({
        title: '请输入委托人姓名',
        icon: 'none',
      })
      return
    }
    if (!delegatePhone) {
      wx.showToast({
        title: '请输入委托人电话',
        icon: 'none',
      })
      return
    }
    if (!checker) {
      wx.showToast({
        title: '请输入验收人员',
        icon: 'none',
      })
      return
    }
    if (!checkDate) {
      wx.showToast({
        title: '请选择验收日期',
        icon: 'none',
      })
      return
    }
    if (!problemOne || problemOneImage.length < 9 || !problemTwo || problemTwoImage.length < 9 || !problemThree || problemThreeImage.length < 9 || !problemFour || problemFourImage.length < 9 || !problemFive || problemFiveImage.length < 9 || !problemSix || problemSixImage.length < 9 || !problemSeven || problemSevenImage.length < 9 || !problemEight || problemEightImage.length < 9 || !problemNine || problemNineImage.length < 9 || !problemTen || problemTenImage.length < 9) {
      wx.showToast({
        title: '请将检验项目问题按要求填写完整',
        icon: 'none',
      })
      return
    }
    if (!signatureImgId) {
      wx.showToast({
        title: '请完成业主签名',
        icon: 'none',
      })
      return
    }
    const inspector = wx.getStorageSync('inspector-info')
    const { token: Authorization } = JSON.parse(inspector)
    const params = {
      area,
      checkName: checker,
      checkTime: formatTime(new Date(checkDate)),
      city: city.toString(),
      clientName: delegateName,
      phone: delegatePhone,
      problemEight,
      problemEightImage: problemEightImage.map(item => item.fileId),
      problemFive,
      problemFiveImage: problemFiveImage.map(item => item.fileId),
      problemFour,
      problemFourImage: problemFourImage.map(item => item.fileId),
      problemNine,
      problemNineImage: problemNineImage.map(item => item.fileId),
      problemOne,
      problemOneImage: problemOneImage.map(item => item.fileId),
      problemSeven,
      problemSevenImage: problemSevenImage.map(item => item.fileId),
      problemSix,
      problemSixImage: problemSixImage.map(item => item.fileId),
      problemTen,
      problemTenImage: problemTenImage.map(item => item.fileId),
      problemThree,
      problemThreeImage: problemThreeImage.map(item => item.fileId),
      problemTwo,
      problemTwoImage: problemTwoImage.map(item => item.fileId),
      propertyNo: house,
      propertyNuber: building,
      remark,
      signatureId: signatureImgId,
    }
    if (this.id) {
      params.id = this.id
      await modifyReport(params, {
        header: {
          Authorization
        },
      })
    } else {
      await genReport(params, {
        header: {
          Authorization
        },
      })
    }

    wx.showToast({
      title: '提交成功',
      icon: 'none',
    })
    setTimeout(() => {
      wx.navigateBack()
    }, 1000)

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { id } = options || {};
    if (id) {
      this.id = id;
      let data = wx.getStorageSync('reportDetail')
      if (data) {
        data = JSON.parse(data)
        this.setData({
          ...data,
          signatureImgId: data.signatureIdList[0].fileId,
          signatureImgPath: data.signatureIdList[0].fileUrl,
          house: data.propertyNo,
          building: data.propertyNuber,
          checker: data.checkName,
          checkDate: new Date(data.checkTime).getTime(),
          checkDateFormat: formatTime(new Date(data.checkTime)),
          delegatePhone: data.phone,
          delegateName: data.clientName,
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})